﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Threading;
using System.Globalization;
using University.Workshop.DataAccess;
using University.Workshop.Model;
using University.Workshop.DataAccess.LanguagePack.ClientLanguagePack;

namespace University.Workshop.ClientApp
{
    /// <summary>
    /// Interaction logic for Wheel.xaml
    /// </summary>
    public partial class Wheel : Window
    {
        public bool Next{get;set;}
        private bool Rigth = true;
        private TransformGroup GroupWheel;
        private RotateTransform RotateWheel = new RotateTransform(0);
        private int Angle=0;
        private bool isTest;
        private User user;
        private string LastText="0";
        public string Parameter { get; set; }
        private long []Price=new long[24];
        private Thread any;
        private int InitialPosition=0;
        private Client client = new Client();
        public bool Banned = false;
        private string selectedLanguage;
        public Wheel()
        {
            InitializeComponent();
            /*GroupWheel = new TransformGroup();
            GroupWheel.Children.Add(RotateWheel);
            Force.ApplyTemplate();
            ((Panel)Force.Template.FindName("Animation", Force)).Background = Brushes.White;*/
         
        }
        public void ApplyLanguage()
        {
            ForceButton.Content=ClientLanguagePack.WheelForceButton;
            Initial.Content=ClientLanguagePack.WheelInitial;
            label1.Content=ClientLanguagePack.WheelLabel1;
            labelChip.Content=ClientLanguagePack.WheelLabelChip;
            labelWelcome.Content=ClientLanguagePack.WheelWelcome;
        }
        public void FillPrice(long Value)
        {
            Price[0] = 10 * Value; Price[1] = (-1) * Value; Price[2] = (-1) * Value; Price[3] = Value / 2; Price[4] = (-1) * (Value / 4); Price[5] = Value; Price[6] = (-1) * Value; Price[7] = Value / 4; Price[8] = (-1) * Value / 2; Price[9] = Value;
            Price[10] = (-1) * Value / 2; Price[11] = Value / 2; Price[12] = (-1) * Value / 2; Price[13] = Value; Price[14] = (-1) * Value / 4; Price[15] = Value; Price[16] = (-1) * Value / 4; Price[17] = Value / 4; Price[18] = Value / 2; Price[19] = Value *2;
            Price[20] = (-1) * Value / 2; Price[21] = (-1) * Value / 4; Price[22] = Value / 4; Price[23] = (-1) * Value;
        }
        public Wheel(User NewUser, bool isTest, string Language)
        {
            InitializeComponent();
            selectedLanguage = Language;
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(selectedLanguage);
            ApplyLanguage();
            
            user = NewUser;
            BetBox.MaxLength = user.Chips.ToString().Length;
            this.isTest = isTest;
                
            
                GroupWheel = new TransformGroup();
            GroupWheel.Children.Add(RotateWheel);
            Force.ApplyTemplate();
            ((Panel)Force.Template.FindName("Animation", Force)).Background = Brushes.White;
            labelName.Content = user.Name;
            labelMoney.Content = user.Chips.ToString(CultureInfo.InvariantCulture);
            BetBox.Text = "1";
            Money.Content = "1";
            any = new Thread(Turn);
        }
        public void Increment()
        {
            while (Next)
            {

                Force.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
            new Action(delegate() { if (Rigth) Force.Value++; else Force.Value--; ; if (Force.Value == Force.Maximum)Rigth = false; if (Force.Value == 0)Rigth = true; }));
                Thread.Sleep(10);
            }

        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {

        }
        public void StartPlay()
        {
            this.Parameter = "Wheel";

            if (client.GetGameStatus(user, this.Parameter))
            {
                Next = true;
                Thread thread = new Thread(new ThreadStart(Increment));
                if(!isTest)
                thread.Start();
            }
            else
            {
                if (!isTest)
                {
                    MessageBox.Show("you played today");
                    this.Close();
                }
            }

        }
        private void ForceButton_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            StartPlay();
        }
        public int InitialTime(int power)
        {
            if (power > 80)
            {
                return 1;
            }
            else
            {
                if (power > 60)
                    return 2;
                else
                {
                    if (power > 40)
                        return 3;
                    else
                        if (power > 20)
                            return 4;
                        else
                            return 5;
                }
            }
        }
        public void Rotate(ref int Sleep, int Power,int NewValue,int SleepValue,int IncrementSleep)
        {
            for (int i = 1; i < NewValue; i++)
            {
                ImageWheel.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
        new Action(delegate()
        {
            RotateWheel.CenterX = 410;
            RotateWheel.CenterY = 360;
            RotateWheel.Angle = Angle;
            ImageWheel.RenderTransform = GroupWheel;
        }));
                Angle++;
                if (Angle == 361) Angle = 0;
                Thread.Sleep(Sleep);
                if (i % (SleepValue) == 0)
                    Sleep += IncrementSleep;


            }
        }
        public void Turn(object NewPower)
        {
            int Power = Convert.ToInt32(NewPower,CultureInfo.InvariantCulture);
            int Initial = InitialTime(Power);
            int Sleep = 1;
            Rotate(ref Sleep,Power,Power*15,10000,0);
            Rotate(ref Sleep, Power,Power*12,Power*5,2);
            Rotate(ref Sleep, Power, Power, 10, 3);
            Sleep = 50;
            Rotate(ref Sleep, Power, Power/4, 10000,0);
            Angle = Angle / 15;
            if (Angle == 24) Angle = 23;
            long MyPrice=Price[Angle];
            string IWin="";
            user.Chips += Price[Angle];
            long Result = user.Chips;
            if (MyPrice < 0) IWin = "You Lose "; else IWin = "You Win";
            labelWelcome.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
            new Action(delegate()
            {

                labelWelcome.Content = IWin;
            }));
            labelName.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
            new Action(delegate()
            {
                if (MyPrice < 0)
                    MyPrice = (-1) * MyPrice;
                labelName.Content = MyPrice.ToString(CultureInfo.InvariantCulture) ;
            }));

            labelMoney.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
            new Action(delegate()
            {
                
                labelMoney.Content = user.Chips.ToString(CultureInfo.InvariantCulture);
            }));
            
            this.Parameter = "14 " + user.Name + " " + Result.ToString(CultureInfo.InvariantCulture);
            client.Send(this.Parameter);
            client.Receive();
            client.SetGameStatus(user,"Wheel");
            if (!isTest)
            {
                if(MyPrice<0)MyPrice*=(-1);
                this.Parameter = IWin +" "+MyPrice.ToString(CultureInfo.InvariantCulture);
                MessageBox.Show(this.Parameter+" ,you can play again in 24 hrs");
                this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
                new Action(delegate()
                {
                    this.Close();
                }));
             }
        }
        private void ForceButton_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Next = false;

            if (Force.Value > 30)
            {
                ForceButton.IsEnabled = false;
                BetBox.IsEnabled = false;
                slider1.IsEnabled = false;
                any = new Thread(Turn);
                any.Start(Force.Value);
            }
            else
            {
                MessageBox.Show("Pull Strong","Strong");
                Force.Value = 0;
              
            }
        }
        
        

        
        private void BetBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            { 
            long Value=Convert.ToInt64(BetBox.Text,CultureInfo.InvariantCulture);
            if (BetBox.Text.Contains("+") || BetBox.Text.Contains("-"))
            {
                BetBox.Text = LastText;
                Value = Convert.ToInt64(LastText);
            }
                LastText = BetBox.Text;
       
            if (Value > user.Chips)
            {
                Value = user.Chips;
                LastText = user.Chips.ToString();
                BetBox.Text = user.Chips.ToString();
            }
            if (Value <= 0)
            {
                Value = 1;
                LastText = "1";
                BetBox.Text = "1";
            }
            Money.Content = (Value).ToString(CultureInfo.InvariantCulture);
            FillPrice(Value);
                ForceButton.IsEnabled = true;
            }
            catch(FormatException)
            {
                if (BetBox.Text != "")
                {
                    if (BetBox.Text.Length > 1)
                        BetBox.Text = LastText;
                    else
                    {
                        BetBox.Text = "";
                        ForceButton.IsEnabled = false;
                        Money.Content = "enter a value";
                    }
                }
                else
                {
                    ForceButton.IsEnabled = false;
                    Money.Content = "enter a value";
                }
            }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
                bool Message = false;
                if (any.IsAlive)
                {
                    any.Abort();
                    Message = true;
                }
                if (!Banned)
                {
            
                if (Message)
                {
                    this.Parameter = "if you retire you will lose the bet, are you sure?";
                    MessageBoxResult result = MessageBox.Show(this.Parameter, "Warning", MessageBoxButton.YesNo);
                    if (result == MessageBoxResult.No)
                    {
                        e.Cancel = true;
                        Angle = InitialPosition;
                        any = new Thread(Turn);
                        any.Start(Force.Value);
                    }
                    else
                    {
                        user.Chips -= Convert.ToInt64(Money.Content, CultureInfo.InvariantCulture);
                        this.Parameter = "14 " + user.Name + " " + user.Chips.ToString(CultureInfo.InvariantCulture);
                        client.Send(this.Parameter);
                        client.Receive();
                        this.Parameter = "17 " + user.Name + " Wheel " + DateTime.Now.AddDays(1).ToString(CultureInfo.InvariantCulture).Replace(' ', '_');
                        client.Send(this.Parameter);
                        client.Receive();
                    }
                }
            }
        }

        private void slider1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            InitialPosition =Convert.ToInt32(slider1.Value,CultureInfo.InvariantCulture);
            Angle = InitialPosition;
            RotateWheel.CenterX = 410;
            RotateWheel.CenterY = 360;
            RotateWheel.Angle = InitialPosition;
            ImageWheel.RenderTransform = GroupWheel;
            
        }

        public void Ban()
        {
            Banned = true;
            Close();
        }
    }
}
